package com.kgcx.oagateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.bean.RequestData;
import com.kgcx.common.client.system.client.OaLogClient;
import com.kgcx.common.client.system.pojo.OaLog;
import com.kgcx.common.utils.TokenUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 吴刚林
 * @date 2018/3/19
 */
@Component
@Slf4j
public class LogFilter extends ZuulFilter {

    private static String[] PWD_KEYS = {"password", "passWord", "pwd"};

    @Autowired
    private OaLogClient oaLogClient;

    private String[] notLogInterface = {"/system/sys/v1/menu/queryAll", "/system/dict/getDictList"};

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //if (ctx.getResponse().getStatus() == HttpStatus.SC_OK) {
        String token = request.getHeader("token");
        String account = "";
        if (StringUtils.isNotBlank(token)) {
            if (!ArrayUtils.contains(notLogInterface, request.getServletPath())) {
                Claims claims = TokenUtils.getClaims(token);
                account = claims.getId();
            }
        } else if ("/system/sys/user/sysUserlogin".equalsIgnoreCase(request.getServletPath())) {
            account = request.getParameter("account");
        }
        if (StringUtils.isNotBlank(account)) {
            OaLog oaLog = new OaLog();
            //oaLog.setUserId(Long.valueOf(id));
            oaLog.setAccount(account);
            oaLog.setInterfaceName(request.getServletPath());
            String s = new RequestData(request).toString();
            JSONObject jsonObject = JSON.parseObject(s);
            for (String pwdKey : PWD_KEYS) {
                if (jsonObject.containsKey(pwdKey)) {
                    jsonObject.remove(pwdKey);
                }
            }
            oaLog.setRequest(jsonObject.toJSONString());
            oaLog.setResponse(ctx.getResponse().toString());
            oaLogClient.addOaLog(oaLog);

        }
        //}
        return null;
    }
}
